<template>
  <div id="app">
    <!-- Logo+标题 -->
    <p>
      <el-row>
        <el-col :span="17" id="logo_font">
          <i class="el-icon-s-goods"></i>{{title}}
        </el-col>
        <!-- 登录 -->
        <el-col :span="2">
          <el-button type="text" @click="dialogVisible1 = true">
            <el-button type="primary" icon="el-icon-s-custom" v-show="dialog_visible1">登录</el-button>
          </el-button>
          <el-dialog title="欢迎您登录!" :visible.sync="dialogVisible1" width="30%" :before-close="handleClose">
            <el-form :model="form" status-icon :rules="rules" ref="ruleForm">
              <el-row>
                <el-col>
                  <el-form-item label="手机号:" :label-width="formLabelWidth" prop="account">
                    <el-input type="text" v-model="form.account" autocomplete="off" @blur="fillPhone()"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="7">
                  <el-form-item label="验证码:" :label-width="formLabelWidth" prop="phonecode">
                    <el-input type="text" v-model="form.phonecode" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <div id="code">
                    <el-button type="primary" round id="code" @click="code()" :disabled="disable">获取验证码</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible1 = false">取 消</el-button>
              <el-button type="primary" @click="userLogin()" :disabled="login">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
        <!-- 退出登录 -->
        <el-col :span="2">
          <el-button type="text">
            <el-button type="primary" icon="el-icon-circle-close" @click="exit()" v-show="dialog_visible3">退出登录</el-button>
          </el-button>
        </el-col>

        <div id="face" v-show="dialog_visible2">
          <div class="demo-basic--circle">
            <div class="block">
              <el-avatar :size="50" :src="circleUrl"></el-avatar>
            </div>
          </div>
          <div class="sub-title">{{circle}}</div>
        </div>
      </el-row>
    </p>

    <!-- 轮播图 -->
    <el-carousel :interval="2000" type="card" height="350px">
      <el-carousel-item>
        <img src="https://img12.360buyimg.com/n1/jfs/t1/104692/30/19292/102657/5e9d327eEfdf4cfeb/a4ccd28b8b593670.jpg">
      </el-carousel-item>
      <el-carousel-item>
        <img src="https://img10.360buyimg.com/n1/jfs/t1/102333/13/19389/168068/5e9e8225Eafb452b9/9094755927324083.jpg">
      </el-carousel-item>
      <el-carousel-item>
        <img src="https://img13.360buyimg.com/n1/jfs/t1/99531/30/9201/63403/5e0abca8E0ff58505/e089d403a28d5a4c.jpg">
      </el-carousel-item>
      <el-carousel-item>
        <img src="https://img13.360buyimg.com/n1/jfs/t1/136722/37/3809/129029/5f02ce97E51442b47/663e71bea0a2b5d5.jpg">
      </el-carousel-item>
      <el-carousel-item>
        <img src="https://img13.360buyimg.com/n1/jfs/t1/142665/26/1863/57007/5efc4b29E11c5a892/d9e862238a04dd38.jpg">
      </el-carousel-item>
    </el-carousel>

    <!-- 页面跳转按钮 -->
    <div>
      <el-button type="success" plain @click="productionType()"><i class="el-icon-platform-eleme buyer_info"></i>商品分类</el-button>
      <el-button type="success" plain>目标二</el-button>
      <el-button type="success" plain @click="car()"><i class="el-icon-shopping-bag-1 buyer_info"></i>购物车</el-button>
      <el-button type="success" plain @click="order()"><i class="el-icon-s-finance buyer_info"></i>订单中心</el-button>
      <el-button type="success" plain @click="center()"><i class="el-icon-s-custom buyer_info"></i>个人中心</el-button>
    </div>

    <!-- 分割线 -->
    <el-divider></el-divider>

    <!-- 搜索框 -->
    <div id="select">
      <el-row class="demo-autocomplete">
        <el-col :span="12">
          <el-autocomplete class="inline-input" v-model="state1" :fetch-suggestions="querySearch" placeholder="搜索你心仪的商品"
            @select="handleSelect" prefix-icon="el-icon-search"></el-autocomplete>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" icon="el-icon-search" @click="select()">搜索</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 分割线 -->
    <el-divider></el-divider>

    <!-- 商品显示 -->
    <div class="demo-image__preview">
      <div id="goods" v-for="i in result">
        <div>
          <el-image style="width: 300px; height: 300px" :src="'http://localhost:8080/fileDownload/getProductFace?productsLogo='+i.productPicture"
            :preview-src-list="['http://localhost:8080/fileDownload/getProductFace?productsLogo='+i.productPicture]">
          </el-image>
        </div>
        <div class="right">
          <el-tooltip class="item" effect="dark" content="最新款" placement="right-start">
            <el-button>{{i.productName}}</el-button>
          </el-tooltip>
        </div>
        &nbsp;
        <div class="right">
          <el-tooltip class="item" effect="dark" content="双十一折扣价" placement="right-start">
            <el-button>{{i.productPrice}}&nbsp;元</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="库存" placement="right-start">
            <el-button>{{i.productInventory}}&nbsp;件</el-button>
          </el-tooltip>
        </div>
        &nbsp;
        <div class="right">
          <el-tooltip class="item" effect="dark" content="购买" placement="right-start">
            <el-button @click="buy(i.productPrice,i.productId)">消费</el-button>
          </el-tooltip>
        </div>

        <el-dialog title="购买商品!" :visible.sync="dialog1" width="30%" :before-close="handleClose">
          <el-form :model="form">
            <el-row>
              <el-col>
                <el-form-item label="价格(元):" :label-width="formLabelWidth">
                  <el-input type="text" v-model="productPrice" autocomplete="off" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col>
                <el-form-item label="收货地址:" :label-width="formLabelWidth">
                  <el-input type="text" v-model="productAddress" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col>
                <el-form-item label="收件人姓名:" :label-width="formLabelWidth">
                  <el-input type="text" v-model="productName" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col>
                <el-form-item label="收件人电话:" :label-width="formLabelWidth">
                  <el-input type="text" v-model="productPhone" autocomplete="off" @blur="rePhone()"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialog1 = false">取 消</el-button>
            <el-button type="primary" @click="pay()" :disabled="buyFinal">确认支付</el-button>
          </span>
        </el-dialog>

        &nbsp;
        <div class="right">
          <el-tooltip class="item" effect="dark" content="心爱之物" placement="right-start">
            <el-button>收藏宝贝</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="等待男朋友消费" placement="right-start">
            <el-button>加入购物车</el-button>
          </el-tooltip>
        </div>
        &nbsp;
        <el-rate v-model="value" disabled show-score text-color="#ff9900" score-template="{value}">
        </el-rate>
      </div>
    </div>
    <!-- 分割线 -->
    <el-divider></el-divider>

    <!-- 分页 -->
    <div>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4"
          :page-sizes="[10, 20, 30, 40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <router-view />
  </div>
</template>

<script>
  const axios = require('axios');
  import Qs from 'qs'
  import uuidv1 from 'uuid/v1'
  export default {
    name: 'Index',
    data() {

      var validateUsername = (rule, value, callback) => {

        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;

        if (value === '') {
          callback(new Error('请输入手机号'));
          this.disable = true;
        } else {
          if (!myreg.test(value)) {
            callback(new Error('手机号格式不正确'));
            this.disable = true;
          } else {
            this.disable = false;
            callback();
          }
        }

      };
      var validatePhonecode = (rule, value, callback) => {

        var phone = localStorage.getItem('phone');

        if (value === '') {
          callback(new Error('请输入验证码'));
        } else {

          if (value == phone) {
            this.login = false;
            callback();
          } else {
            this.login = true;
            callback(new Error('验证码错误'));
          }

        }
      };
      return {
        title: "“码”上商城",
        dialogVisible1: false,
        dialogVisible2: false,
        dialog1: false,
        value: 3.7,
        restaurants: [],
        state1: '',
        currentPage1: 5,
        currentPage2: 5,
        currentPage3: 5,
        currentPage4: 1,
        currentSize: 10,
        total: 0,
        result: '',
        disable: true,
        login: true,
        buyFinal: true,
        dialog_visible1: true,
        dialog_visible2: false,
        dialog_visible3: false,
        circle: '',
        circleUrl: '',
        productPrice: 0,
        productId:'',
        productAddress: '',
        productName: '',
        productPhone: '',
        //登录表单
        form: {
          account: '',
          password: '',
          phonecode: ''
        },
        formLabelWidth: '120',
        rules: {
          account: [{
            validator: validateUsername,
            trigger: 'blur'
          }],
          phonecode: [{
            validator: validatePhonecode,
            trigger: 'blur'
          }]
        },
        choose: false // 记住密码,默认不选中
      }
    },
    methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      loadAll() {
        return [{
          "value": "华为mate30Pro"
        }, {
          "value": "牛津英语电子词典"
        }, {
          "value": "有线游戏鼠标"
        }, {
          "value": "头戴式Ⅴr一体机"
        }, {
          "value": "地板刷卫生间刷"
        }, {
          "value": "开学防疫包"
        }, {
          "value": "天红美厨蒸饭柜"
        }, {
          "value": "新鲜折耳根鱼腥草"
        }, {
          "value": "蒙牛圣牧有机纯牛奶"
        }];
      },
      handleSelect(item) {
        console.log(item);
      },
      center: function() {
        this.$router.push('/buyerInfo');
      },
      productionType: function() {
        this.$router.push('/productionType');
      },
      //短信验证
      code: function() {
        var data = Qs.stringify({
          "phone": this.form.account
        });
        axios.post('http://localhost:8080/user/phoneCode', data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          })
          .then(response => {
            // 存储在本地缓存
            localStorage.setItem("phone", response.data);
          })
          .catch(function(error) {
            alert("异步请求失败！");
          });

      },
      userLogin: function() {
        var phone = this.form.account;
        axios.get('http://localhost:8080/user/login', {
            params: {
              userPhone: phone
            }
          })
          .then(response => {

            localStorage.setItem('flag', 'true');
            localStorage.setItem('name', phone);
            localStorage.setItem('face', 'http://localhost:8080/fileDownload/getProductFace?productsLogo=test.jpg');

            if (response.data == true) {

              this.$confirm('用户存在，登录成功！', '提示', {
                confirmButtonText: '确定',
                type: 'info'
              }).then(() => {
                this.$message({
                  type: 'success',
                  message: '登录成功!'
                });
              });

              this.dialogVisible1 = false;
              this.dialog_visible1 = false;
              this.dialog_visible2 = true;
              this.dialog_visible3 = true;

              this.circle = phone;
              this.circleUrl = 'http://localhost:8080/fileDownload/getProductFace?productsLogo=test.jpg';

            } else {

              this.$confirm('用户不存在，系统进行注册！', '提示', {
                confirmButtonText: '确定',
                type: 'info'
              }).then(() => {
                this.$message({
                  type: 'success',
                  message: '系统注册!'
                });
              });

              axios.get('http://localhost:8080/user/insertUser', {
                  params: {
                    userPhone: phone
                  }
                })
                .then(response => {
                  if (response.data == true) {

                    this.$confirm('用户已经成功注册！', '提示', {
                      confirmButtonText: '确定',
                      type: 'info'
                    }).then(() => {
                      this.$message({
                        type: 'success',
                        message: '登陆成功!'
                      });
                    });
                    this.dialogVisible1 = false;
                    this.dialog_visible1 = false;
                    this.dialog_visible2 = true;
                    this.dialog_visible3 = true;

                    this.circle = phone;

                    this.circleUrl = 'http://localhost:8080/fileDownload/getProductFace?productsLogo=test.jpg';
                  } else {
                    alert("注册失败！");
                  }
                })
                .catch(function(error) {
                  alert("异步请求失败！");
                })
            }
          })
          .catch(function(error) {
            alert("异步请求失败！");
          });
      },
      rePhone: function() {

        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;

        if (!myreg.test(this.productPhone)) {
          this.$confirm('手机号格式不正确', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            this.$message({
              type: 'warning',
              message: '请重新输入！'
            });
          });
          this.productPhone = '';

        } else {
          this.buyFinal = false;
        }
      },
      //用户登录
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('登录成功!');
            // 发送axios进行登录
            axios.get(" ", {
              params: {
                username: this.form.account,
                password: this.form.password,
                phonecode: this.form.phonecode
              }
            }).then(response => {
              console.log(response);
              // 判断响应回来的msg
              if (response.data.msg == 'success') { // 登录成功
                // 0 提示框
                this.$message({
                  showClose: true,
                  message: '登录成功',
                  type: 'success'
                });
                // 1判断是否记住密码,如果选择记住密码.则将用户数据存储到localStorge中
                if (this.choose == true) {
                  localStorage.setItem(this.form.account, this.form.password);
                } else {
                  localStorage.removeItem(this.form.account);
                }
                // 2转换路由 跳转到文章显示页面
                this.$router.push("/index");

              } else { // 登录失败
                // 0 提示框
                this.$message.error('账号或者密码错误，登录失败！');
              }
            }).catch(error => {
              alert('axios异步请求失败!');
            })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      fillPhone: function() {

      },
      car: function() {
        // 跳转购物车页面
        this.$router.push('/carInfo');
      },
      order: function() {
        // 跳转订单页面
        this.$router.push('/orderInfo');
      },
      ajax: function() {
        // 加载商品信息 + 分页
        axios.get('http://localhost:8080/product/allByPage', {
            params: {
              pageNum: this.currentPage4,
              pageSize: this.currentSize
            }
          })
          .then(response => {
            this.result = response.data.list;
            this.total = response.data.total;
          })
          .catch(function(error) {
            alert("异步请求失败！");
          });
      },
      handleSizeChange(val) {
        this.currentSize = val;
        this.ajax();
        console.log(`每页` + this.currentSize);
      },
      handleCurrentChange(val) {
        this.currentPage4 = val;
        this.ajax();
        console.log(`当前页` + this.currentPage4);
      },
      select: function() {
        axios.get('http://localhost:8080/product/likeName', {
            params: {
              productName: this.state1,
              pageNum: this.currentPage4,
              pageSize: this.currentSize
            }
          })
          .then(response => {
            this.result = response.data.list;
            this.total = response.data.total;
          })
          .catch(function(error) {
            alert("异步请求失败！")
          });
      },
      buy: function(price,id) {

        var name = localStorage.getItem('name');

        if (name != null) {
          this.dialog1 = true;
          this.productPrice = price;
          this.productId = id;

        } else {
          this.$confirm('对不起，请您登录！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            this.$message({
              type: 'warning',
              message: '请您登录!'
            });
          });
        }
      },
      exit: function() {
        localStorage.removeItem('flag');
        localStorage.removeItem('name');
        localStorage.removeItem('face');
        localStorage.removeItem('phone');

        this.dialog_visible1 = true;
        this.dialog_visible2 = false;
        this.dialog_visible3 = false;
      },
      pay: function(productId) {
        console.log("价格" + this.productPrice);
        console.log("地址" + this.productAddress);
        console.log("姓名" + this.productName);
        console.log("电话" + this.productPhone);
        console.log("商品编号" + this.productId);

        var name = localStorage.getItem('name');
        axios.get('http://localhost:8080/user/findId', {
            params: {
              userPhone: name
            }
          })
          .then(response => {


            if (response.data != null) {
              // 订单编号
              var id = "A202000000"+parseInt(Math.random()*1000000000);
              var num = this.productPrice;

              axios.get('http://localhost:8080/ordersController/insertOrder', {
                  params: {
                    orderId:id,
                    userId: response.data,
                    orderTotalPrice: num,
                    orderReceivePhone: this.productPhone,
                    orderReceiveName: this.productName,
                    orderReceiveAddress: this.productAddress,
                    productId:this.productId
                  }
                })
                .then(response => {
                  // 跳转沙箱
                  location.href = 'http://localhost:8080/order/payOrder?orderId='+id+"&cost="+num;
                })
                .catch(function(error) {
                  alert("异步请求失败！");
                });
            }
          })
          .catch(function(error) {
            alert("异步请求失败！");
          });

      }
    },
    mounted() {
      // 商品信息
      this.ajax();
      // 输入框提示
      this.restaurants = this.loadAll();

      var flag = localStorage.getItem('flag');
      var name = localStorage.getItem('name');
      var face = localStorage.getItem('face');
      localStorage.getItem('face');
      if (flag == 'true') {
        this.dialog_visible1 = false;
        this.dialog_visible2 = true;
        this.dialog_visible3 = true;

        this.circle = name;
        this.circleUrl = face;
      } else {
        this.dialog_visible1 = true;
        this.dialog_visible2 = false;
        this.dialog_visible3 = false;
      }
    }
  }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 30px;
  }

  #logo_font {
    font-size: 30px;
    line-height: 1.7;
    font-family: "PingFang SC";
    text-align: left;
    margin-left: 100px;
  }

  .buyer_info {
    text-decoration: none;
    font-family: "PingFang SC";
    font-size: 20px;
    line-height: 10px;
  }

  .tag {
    height: 50px;
    width: 120px;
  }

  .el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }

  #goods {
    height: 570px;
    width: 444px;
    display: inline-block;
  }

  #tip {
    display: inline;
  }

  .box {
    width: 200px;

    .top {
      text-align: center;
    }

    .left {
      float: left;
      width: 60px;
    }

    .right {
      width: 60px;
    }

    .bottom {
      clear: both;
      text-align: center;
    }

    .item {
      margin: 4px;
    }

    .left .el-tooltip__popper,
    .right .el-tooltip__popper {
      padding: 8px 10px;
    }
  }

  #select {
    margin-left: 150px;
  }

  .inline-input {
    width: 700px;
  }

  #code {
    margin-top: 19px;
    margin-left: 15px;
  }

  #face {
    height: 100px;
    width: 100px;
    margin-left: 1050px;
    margin-top: 10px;
  }
</style>
